using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Smo;

namespace DataPopulation
{
    public partial class OptionsDlg : Form
    {
        private XmlDocument xmlDoc;
        private string configFile;
        private string connstr;
        private string psurl;

        public OptionsDlg()
        {
            InitializeComponent();
            LoadSettings();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            SaveSettings();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            dlgBrowse.SelectedPath = txtLogPath.Text;
            if (dlgBrowse.ShowDialog() == DialogResult.OK)
            {
                txtLogPath.Text = dlgBrowse.SelectedPath;
            }
        }

        private void chkLoggingEnabled_CheckedChanged(object sender, EventArgs e)
        {
            chkLogAll.Enabled = chkLoggingEnabled.Checked;
            txtLogPath.Enabled = chkLoggingEnabled.Checked;
            btnBrowse.Enabled = chkLoggingEnabled.Checked;
        }

        public int EntityLimit
        {
            get { return Convert.ToInt32(txtEntityLimit.Text); }
            set { txtEntityLimit.Text = value.ToString(); }
        }

        public bool LoggingEnabled
        {
            get { return chkLoggingEnabled.Checked; }
            set { chkLoggingEnabled.Checked = value; }
        }

        public bool LogAll
        {
            get { return chkLogAll.Checked; }
            set { chkLogAll.Checked = value; }
        }

        public string LogPath
        {
            get { return txtLogPath.Text; }
            set { txtLogPath.Text = value; }
        }

        public string PSUrl
        {
            get { return psurl; }
            set { psurl = value; }
        }

        public string ConnectionString
        {
            get { return connstr; }
        }

        public bool EnableRetry
        {
            get { return chkRetry.Checked; }
            set { chkRetry.Checked = value; }
        }

        public void SaveSettings()
        {
            try
            {
                XmlNode nodeSettings = xmlDoc.SelectSingleNode("configuration/applicationSettings/DataPopulation.Properties.Settings");
                if (nodeSettings != null)
                {
                    XmlNode nodeValue;
                    foreach (XmlNode node in nodeSettings.ChildNodes)
                    {
                        nodeValue = node.SelectSingleNode("value");
                        switch (node.Attributes["name"].Value)
                        {
                            case "PSUrl":
                                nodeValue.InnerText = psurl;
                                break;

                            case "EntityLimit":
                                nodeValue.InnerText = txtEntityLimit.Text;
                                break;

                            case "LoggingEnabled":
                                nodeValue.InnerText = chkLoggingEnabled.Checked.ToString();
                                break;

                            case "LogAll":
                                nodeValue.InnerText = chkLogAll.Checked.ToString();
                                break;

                            case "LoggingPath":
                                nodeValue.InnerText = txtLogPath.Text;
                                break;

                            case "AutoRetry":
                                nodeValue.InnerText = chkRetry.Checked.ToString();
                                break;

                            case "DBServer":
                                nodeValue.InnerText = cbServer.Text;
                                break;

                            case "DBName":
                                nodeValue.InnerText = cbDatabase.Text;
                                break;
                        }
                    }
                }
                connstr = String.Concat("Data Source=", cbServer.Text, ";Initial Catalog=", cbDatabase.Text, ";Integrated Security=True");
                xmlDoc.Save(configFile);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void LoadSettings()
        {
            try
            {
                xmlDoc = new XmlDocument();
                configFile = Application.ExecutablePath + ".config";
                xmlDoc.Load(configFile);

                XmlNode nodeSettings = xmlDoc.SelectSingleNode("configuration/applicationSettings/DataPopulation.Properties.Settings");
                XmlNode nodeValue;
                foreach (XmlNode node in nodeSettings.ChildNodes)
                {
                    nodeValue = node.SelectSingleNode("value");
                    switch (node.Attributes["name"].Value)
                    {
                        case "PSUrl":
                            psurl = nodeValue.InnerText;
                            break;

                        case "EntityLimit":
                            txtEntityLimit.Text = nodeValue.InnerText;
                            break;

                        case "LoggingEnabled":
                            chkLoggingEnabled.Checked = Convert.ToBoolean(nodeValue.InnerText);
                            break;

                        case "LogAll":
                            chkLogAll.Checked = Convert.ToBoolean(nodeValue.InnerText);
                            break;

                        case "LoggingPath":
                            txtLogPath.Text = nodeValue.InnerText;
                            break;

                        case "AutoRetry":
                            chkRetry.Checked = Convert.ToBoolean(nodeValue.InnerText);
                            break;

                        case "DBServer":
                            cbServer.Text = nodeValue.InnerText;
                            break;

                        case "DBName":
                            cbDatabase.Text = nodeValue.InnerText;
                            break;
                    }
                }
                connstr = String.Concat("Data Source=", cbServer.Text, ";Initial Catalog=", cbDatabase.Text, ";Integrated Security=True");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void cbServer_DropDown(object sender, EventArgs e)
        {
            if (cbServer.Items.Count > 0) return;

            Cursor = Cursors.WaitCursor;

            try
            {
                SmoApplication.EnumAvailableSqlServers(false);
                DataTable dtServers = SmoApplication.EnumAvailableSqlServers(false);
                cbServer.Items.Clear();
                cbDatabase.Text = "";
                foreach (DataRow dr in dtServers.Rows)
                {
                    string sqlServerName = dr["Server"].ToString();
                    if (dr["Instance"] != null && dr["Instance"].ToString().Length > 0)
                    {
                        sqlServerName += @"\" + dr["Instance"].ToString();
                    }
                    cbServer.Items.Add(sqlServerName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void cbDatabase_DropDown(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            try
            {
                if (cbServer.Text.Length == 0) return;
                Server svr = new Server(cbServer.Text);
                cbDatabase.Items.Clear();
                foreach (Database db in svr.Databases)
                {
                    cbDatabase.Items.Add(db.Name);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
    }
}